<template>
    <div class="scheme">
        <el-drawer title="筛选方案列表" :visible.sync="drawer" direction="rtl" size='600px' @close="outDrawerClose">
            <div class="createWay clearfix">
                <my-button size="mini" type="primary" class="el-icon-circle-plus-outline scheme"
                    @btnClick="innerDrawerOpen('create')" :disabled='editableTabs.length >= 20'>
                    创建筛选方案
                </my-button>
                <span class="el-icon-warning-outline">最多可创建20条</span>
            </div>
            <el-table :data="editableTabs"
                :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                :cell-style="{color:'#5a5a5a',fontSize:'12px'}" border>
                <el-table-column prop="name" label="筛选方案名称"></el-table-column>
                <el-table-column label="操作" width='200'>
                    <template slot-scope="scope">
                        <my-button type="text" size="small" @btnClick="innerDrawerOpen('edit',scope.row)"
                            >
                            编辑
                        </my-button>
                        <el-popconfirm placement='top' confirm-button-text='删除' @confirm="confirmDel(scope.row.id,scope.$index,scope.row.name)"
                            title="确认删除筛选方案？删除后不可恢复">
                            <el-button slot="reference" type="text" size="small" style="margin-left:10px">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-drawer :title="(instructType == 'create' ? '创建' : '编辑') + '方案'" :append-to-body="true" :visible.sync="innerDrawer" size='460px'
                @close="drawerClose" @open="open">
                <div class="scheme_form">
                    <el-form :model="wayForm" :rules="rules" ref="ruleForm" label-width="80px" size="mini">
                        <el-form-item label="方案名称" prop="name">
                            <el-input v-model="wayForm.name" placeholder="请填写"></el-input>
                        </el-form-item>
                        <el-form-item label="使用范围" prop="userIdName">
                            <select-tree ref="tree" :instructType="instructType" :editInfo="editInfo"></select-tree>
                        </el-form-item>
                        <el-form-item label="二级分组" prop="secondGroup">
                            <el-select v-model="wayForm.secondGroup" clearable>
                                <el-option v-for="item in secondGroup" :key="item.value" :label="item.chineseName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-popover placement="bottom" trigger="click" width="402" v-model="popShow">
                                <el-checkbox-group v-model="checkList">
                                    <el-checkbox v-for="item in checkGroup" :label="item.name" :key="item.idx"
                                        style="width:50%">
                                        {{item.name}}
                                    </el-checkbox>
                                    <div style="margin-bottom: 10px;font-size: 12px;color: rgba(0, 0, 0, .85);">自定义字段
                                    </div>
                                    <el-checkbox v-for="item in customFieldList" :label="item.name" :key="item.idx"
                                        style="width:50%">
                                        {{item.name}}
                                    </el-checkbox>
                                </el-checkbox-group>
                                <div class="operate">
                                    <el-button size="mini" @click='popShow = false'>取 消</el-button>
                                    <el-button type="primary" size="mini" @click='popClick'>确 定</el-button>
                                </div>
                                <el-button size="mini" type="primary" class="el-icon-circle-plus-outline" plain
                                    slot="reference" style='padding:7px 12px'>
                                    添加筛选条件</el-button>
                            </el-popover>
                            <span
                                style="fontSize:12px;color:rgba(0,0,0,.65);margin:0 10px">已添加{{checkList.length}}个</span>
                            <el-button type="text" @click='reset'>重置</el-button>
                        </el-form-item>
                        <scheme :formDataList='formDataList' ref='customEvent' :width='80'
                            :screenCondition='screenCondition'></scheme>
                    </el-form>
                </div>
                <div class="operate" style="textAlign:center">
                    <el-button size="mini" @click="innerDrawer = false" style="padding:7px 35px">取 消</el-button>
                    <el-button type="primary" size="mini" @click="handleClose" style="padding:7px 35px">确 定</el-button>
                </div>
            </el-drawer>
        </el-drawer>
    </div>
</template>

<script>
    const defaultSecondGroup = [
        {
            id: '产品属性',
            chineseName: '产品属性'
        }
    ]
    import {
        spDel,
        screenPlanHandle
    } from '@/api/produceController'
    import {
        customFieldOther
    } from '@/api/customFieldController'
    import scheme from '@/components/scheme'
    import selectTree from '@/components/selectTree'
    export default {
        data() {
            return {
                wayForm: {
                    type: 2,
                    name: '',
                    userIdName: [],
                    userId: '',
                    depId: '',
                    secondGroup: '产品属性',
                    id: '',
                    workOrderSearchVo: {
                        configData: []
                    }
                },
                drawer: false,
                innerDrawer: false,
                rules: {
                    name: [{
                            required: true,
                            message: '方案名称必填',
                            trigger: 'blur'
                        },
                        {
                            max: 20,
                            message: '方案名称长度不能大于20',
                            trigger: 'change'
                        }
                    ],
                    secondGroup: [{
                        required: true,
                        message: '二级分组必填',
                        trigger: 'change'
                    }],
                },
                secondGroup: [],
                popShow: false,
                checkList: [],
                arrayList: [],
                checkGroup: [{
                        label: 'productCode',
                        name: '产品编号',
                        placeholder: '请输入产品编号',
                        key: 'srk',
                        idx: 1,
                        i_key: 'productCode'
                    },
                    {
                        label: 'productName',
                        name: '产品名称',
                        placeholder: '请输入产品名称',
                        key: 'srk',
                        idx: 2,
                        i_key: 'productName'
                    },
                    {
                        label: 'productSpecification',
                        name: '产品规格',
                        placeholder: '请输入产品规格',
                        key: 'srk',
                        idx: 3,
                        i_key: 'productSpecification'
                    },
                    {
                        label: 'attribute',
                        name: '产品属性',
                        placeholder: '请选择',
                        key: 'sel',
                        idx: 4,
                        i_key: 'attribute',
                        node: {
                            default: '',
                            isRadio: true,
                            options: [{
                                    value: 0,
                                    label: '自制'
                                },
                                {
                                    value: 1,
                                    label: '外购'
                                },
                                {
                                    value: 2,
                                    label: '委外'
                                }
                            ]
                        }
                    },
                    {
                        label: ['numDown', 'numUp'],
                        name: '库存数量',
                        key: 'jsk',
                        idx: 5,
                        dis: 'array',
                        i_key: 'num'
                    },
                    {
                        label: ['maximumDown', 'maximumUp'],
                        name: '最大库存',
                        key: 'jsk',
                        idx: 6,
                        dis: 'array',
                        i_key: 'maximum'
                    },
                    {
                        label: ['minimumDown', 'minimumUp'],
                        name: '最小库存',
                        key: 'jsk',
                        idx: 7,
                        dis: 'array',
                        i_key: 'minimum'
                    },
                    {
                        label: ['safeDown', 'safeUp'],
                        name: '安全库存',
                        key: 'jsk',
                        idx: 8,
                        dis: 'array',
                        i_key: 'safe'
                    },
                    {
                        label: 'typeOther',
                        name: '常用筛选',
                        placeholder: '请选择',
                        key: 'sel',
                        idx: 9,
                        i_key: 'typeOther',
                        node: {
                            default: '',
                            isRadio: true,
                            options: [{
                                    value: 0,
                                    label: '库存数量<安全库存'
                                },
                                {
                                    value: 1,
                                    label: '库存数量<最小库存'
                                },
                                {
                                    value: 2,
                                    label: '库存数量>最大库存'
                                }
                            ]
                        }
                    },
                ],
                customFieldList: [],
                formDataList: {
                    formGroup: [],
                    searchForm: {
                        productCode:'',
                        productName:'',
                        productSpecification:'',
                        attribute:'',
                        maximumDown:'',
                        maximumUp:'',
                        minimumDown:'',
                        minimumUp:'',
                        safeDown:'',
                        safeUp:'',
                        typeOther:''
                    },
                },
                enumCustomField: {
                    ipt: {
                        placeholder: '请输入',
                        key: 'srk'
                    },
                    inputNumber: {
                        placeholder: '',
                        key: 'jsk'
                    },
                    datePicker: {
                        placeholder: '',
                        key: 'cki'
                    },
                    selectChecked: {
                        placeholder: '请选择',
                        key: 'sel',
                        node: {
                            default: [],
                            isRadio: false,
                            options: []
                        }
                    },
                    relevanceObject: {
                        placeholder: '请选择',
                        key: 'sel',
                        node: {
                            default: [],
                            isRadio: false,
                            options: []
                        }
                    },
                    selectRadio: {
                        placeholder: '请选择',
                        key: 'sel',
                        node: {
                            default: '',
                            isRadio: true,
                            options: []
                        }
                    },
                },
                allCheckGroup: [],
                instructType: 'create',
                screenCondition: [],
                index: 0,
                editInfo:{
                    userId:'',
                    depId:'',
                    selectNames:''
                }
            }
        },
        props: {
            editableTabs: {
                type: Array,
                default: () => []
            }
        },
        components: {
            scheme,
            selectTree
        },
        methods: {
            // 自定义字段
            getCustomFieldOther(data) {
                customFieldOther(data).then(res => {
                    //把自定义字段'附件'--'图片'--'关联属性'过滤掉
                    let filterData = res.data.filter(i => {
                        return i.customFieldMess.fieldType != 'upload' &&
                            i.customFieldMess.fieldType != 'picture' &&
                            i.customFieldMess.fieldType != 'relevanceProp'
                    })
                    //获取二级分组(单选框)
                    let group = res.data.filter(i => i.customFieldMess.fieldType == 'selectRadio').map(i => {
                        return {
                            id:i.customFieldId + '',
                            chineseName:i.name
                        }
                    })
                    this.secondGroup = [...defaultSecondGroup,...group]
                    //将自定义字段得每一项构造成类似checkGroup的每一项结构
                    this.customFieldList = filterData.map((i, index) => {
                        let node = {
                            default: [],
                            isRadio: false,
                            options: []
                        }
                        let checkbox = []
                        if (i.customFieldMess.fieldType == 'selectChecked' || i.customFieldMess
                            .fieldType == 'selectRadio') {
                            checkbox = JSON.parse(i.customFieldMess.checkBox)
                            node.default = i.customFieldMess.fieldType == 'selectChecked' ? [] : ''
                            node.isRadio = i.customFieldMess.fieldType != 'selectChecked' //取反
                            node.options = checkbox.map(k => {
                                return {
                                    label: k.value,
                                    value: k.value
                                }
                            })
                        } else if (i.customFieldMess.fieldType == 'relevanceObject') {
                            node.default = []
                            node.isRadio = false
                            node.options = i.objectsValue.map(k => {
                                return {
                                    value: k.code + ' - ' + k.name + ' - ' + (k.specification || ''),
                                    label: k.code + ' - ' + k.name + ' - ' + (k.specification || '')
                                }
                            })
                        }
                        return {
                            label: i.customFieldId,
                            name: i.name,
                            placeholder: this.enumCustomField[i.customFieldMess.fieldType].placeholder,
                            key: this.enumCustomField[i.customFieldMess.fieldType].key,
                            idx: this.checkGroup.length + 1 + index,
                            type: i.customFieldMess.fieldType,
                            i_key: i.customFieldId,
                            node
                        }
                    })
                    this.allCheckGroup = [...this.checkGroup, ...this.customFieldList]

                })
            },
            //筛选方案操作
            getScreenPlanHandle(data) {
                screenPlanHandle(data).then(res => {
                    if (res.code == 200) {
                        this.$emit('getList')
                        this.drawerClose()
                        this.reset()
                        this.innerDrawer = false
                        this.utils.showMsg('方案保存成功', 'success')
                    }
                })
            },
            //确定
            popClick() {
                this.index++
                this.arrayList = []
                this.allCheckGroup.forEach(i => { //将选中的对应复选框展示出来
                    if (this.checkList.indexOf(i.name) != -1) this.arrayList = [...this.arrayList, i]
                })
                this.arrayList.sort((a, b) => a.idx - b.idx) //将每一个表单项按顺序排列
                this.formDataList.formGroup = JSON.parse(JSON.stringify(this.arrayList))
                if (this.instructType === 'edit') {
                    /**
                     * index 作用说明 --  index <= 1 说明用户从编辑进入未通过勾选框状态来对表单项进行增加删除
                        * 当从编辑进入且表单项不为空时 用户更改当前已有得表单项值，再更改勾选框其他表单项，对其进行增加删除
                        此时用户更改过后的表单项值会变为初始编辑进入的值
                     */
                    if (this.index <= 1) this.$nextTick(() => {
                        this.$refs.customEvent.setUp()
                    })
                }
                this.popShow = false
            },
            // 打开筛选方案列表
            drawerOpen() {
                this.getCustomFieldOther({
                    type: 'product'
                })
                this.drawer = true
            },
            //重置
            reset() {
                this.formDataList.formGroup = []
                this.checkList = []
                this.$refs.customEvent.reset()
            },
            //打开内层抽屉
            innerDrawerOpen(way,row) {
                this.screenCondition = way == 'edit' ? JSON.parse(row.screenCondition).configData : []
                this.instructType = way
                this.wayForm.secondGroup = way == 'edit' ?  row.secondGroup : '产品属性'
                if(way == 'edit'){
                    [this.wayForm.name,this.wayForm.id] = [row.name,row.id]
                    this.checkList = []
                    this.editInfo.userId = row.userId
                    this.editInfo.depId = row.depId
                    this.editInfo.selectNames = row.userIdName
                    this.screenCondition.forEach(i => this.checkList = [...this.checkList,i.chineseName])
                    this.popClick()
                }
                this.innerDrawer = true
            },
            //创建--编辑方案
            drawerClose() {
                this.index = 0
                this.reset()
                this.$refs.tree.clearTreeInfo()
                this.$refs.ruleForm.resetFields()
                this.wayForm = this.$options.data().wayForm
            },
            open(){
                this.$nextTick(()=>{
                    this.$refs.tree.handleDefaultValue(this.instructType)
                })
            },
            outDrawerClose() {
                this.$emit('fromOutDrawerClose')
            },
            //删除
            getSpDel(data,payload) {
                spDel(data,payload).then(res => {
                    if (res.code == 200) {
                        if (this.editableTabs.length == 1) this.$emit('lastData')
                        this.$emit('getList',{delIndex:payload.delIndex,name:payload.name})
                        this.utils.showMsg('筛选方案删除成功', 'success')
                    }
                })
            },
            //删除筛选方案
            confirmDel(id,delIndex,name) {
                this.getSpDel({
                    id
                },{delIndex,name})
            },
            //确定
            handleClose() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        let data = JSON.parse(JSON.stringify(this.wayForm))
                        const {userId,depId,selectNames} = this.$refs.tree.getTreeInfo()
                        data.workOrderSearchVo.configData = this.$refs.customEvent.getData()
                        data.userId = userId
                        data.depId = depId
                        data.userIdName = selectNames.toString()
                        this.getScreenPlanHandle(data)
                    } else {
                        return false;
                    }
                });
            },
        }
    }
</script>

<style lang="less" scoped>
    .scheme {

        .el-form {
            /deep/ .el-form-item:last-child {
                margin-bottom: 0;
            }
        }

        .createWay {
            margin-bottom: 20px;

            .el-button--primary {
                float: left;
            }

            .el-icon-warning-outline {
                float: left;
                font-size: 12px;
                color: rgb(155, 155, 155);
                margin-left: 10px;
                margin-top: 9px;
            }
        }

        .scheme_form {
            padding: 20px 20px;
            background-color: rgb(250, 250, 250);
            margin-bottom: 20px;

            /deep/ .el-button--primary {
                border-style: dashed;
            }
        }

        .operate {
            text-align: center;
        }
    }
</style>